// 删除分页条件判断，合并两页表单字段
<template>
  <div class="form-container">
    <el-form
      ref="ruleFormRef"
      :model="newFormInline"
      :rules="formRules"
      label-width="120px"
      class="w-full"
    >
      <el-form-item
        :label="props.formInline.type === 2 ? '调度员名称' : '用户名称'"
        prop="name"
      >
        <el-input
          v-model="newFormInline.name"
          :placeholder="
            props.formInline.type === 2 ? '请输入调度员名称' : '请输入用户名'
          "
        />
      </el-form-item>
      <el-form-item
        v-if="props.formInline.type === 1"
        label="所属区域"
        prop="zoneId"
      >
        <el-cascader
          v-model="newFormInline.zoneId"
          class="w-full"
          :options="zoneOptions"
          :props="cascaderProps"
          placeholder="请选择所属区域"
          clearable
        />
      </el-form-item>
      <el-form-item label="过期时间" prop="expire">
        <el-date-picker
          v-model="newFormInline.expire"
          style="width: 100%"
          type="datetime"
          placeholder="选择过期时间"
          :shortcuts="shortcuts"
        />
      </el-form-item>
      <el-form-item label="备注" prop="comment">
        <el-input
          v-model="newFormInline.comment"
          type="textarea"
          :maxlength="200"
          show-word-limit
          :rows="4"
          placeholder="请输入备注，最多200字"
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, defineProps, defineEmits, watch } from "vue";
import { formRules } from "../componentsUtils/rule/userRules";
import { FormProps } from "../componentsUtils/type/userTypes";
import { ElMessage } from "element-plus";
import { http } from "@/utils/http";
import { changeHttpLink } from "@/utils/test";
import { handleTree } from "@/utils/tree";
import { useDataSyncStore } from "@/store/modules/dataSync";

const emit = defineEmits<{
  "refresh-data": [];
}>();

const props = withDefaults(
  defineProps<{
    //formType?: 1 | 2;
    formInline?: any;
    title?: string;
    originalName?: string;
    categorizeOptions?: { label: string; value: number }[];
    zoneOptions?: { label: string; value: number }[];
  }>(),
  {
    formInline: () => ({
      id: 0,
      no: 0,
      dealerId: 0,
      tenantId: 0,
      zoneId: 0,
      name: "",
      type: 1,
      power: 1,
      defChannel: 0,
      defContact: 0,
      categorizeId: 0,
      refDeviceId: 0,
      disabled: false,
      tel: "",
      bi: 0,
      yun: 0,
      gps: 30,
      expire: () => {
        const date = new Date();
        date.setFullYear(date.getFullYear() + 1);
        return date;
      },
      videoId: "",
      comment: ""
    }),
    title: "",
    originalName: "",
    categorizeOptions: () => [
      {
        label: "默认分类",
        value: 0
      }
    ],
    zoneOptions: () => []
  }
);

const newFormInline = ref(props.formInline);
const ruleFormRef = ref();
const shortcuts = [
  {
    text: "1年",
    value: () => {
      const date = new Date();
      date.setFullYear(date.getFullYear() + 1);
      return date;
    }
  },
  {
    text: "2年",
    value: () => {
      const date = new Date();
      date.setFullYear(date.getFullYear() + 2);
      return date;
    }
  },
  {
    text: "3年",
    value: () => {
      const date = new Date();
      date.setFullYear(date.getFullYear() + 3);
      return date;
    }
  },
  {
    text: "5年",
    value: () => {
      const date = new Date();
      date.setFullYear(date.getFullYear() + 5);
      return date;
    }
  },
  {
    text: "10年",
    value: () => {
      const date = new Date();
      date.setFullYear(date.getFullYear() + 10);
      return date;
    }
  }
];
// 级联选择器属性配置
const cascaderProps = {
  value: "Id",
  label: "Name",
  children: "children",
  emitPath: false, // 只返回最后一级的ID
  checkStrictly: true // 允许选择任意一级
};

// 定义本地响应式变量来引用props
const zoneOptions = computed(() => props.zoneOptions);

// 判断是否为新增场景
const isAdd = computed(() => newFormInline.value.id === 0);

// 监听props变化，确保数据更新时表单能够响应
watch(
  () => props.zoneOptions,
  newZoneOptions => {
    // 当zoneOptions更新时，打印日志确认数据已更新
    console.log("zoneOptions updated:", newZoneOptions);
  },
  { deep: true, immediate: true }
);

watch(
  () => props.formInline,
  newFormInlineData => {
    // 当formInline更新时，同步到本地响应式变量
    if (newFormInlineData) {
      Object.assign(newFormInline.value, newFormInlineData);
    }
  },
  { deep: true, immediate: true }
);

// 监听全局数据更新
const dataSyncStore = useDataSyncStore();
watch(
  () => dataSyncStore.zoneDataTimestamp,
  () => {
    console.log(
      "[UserForm] Detected zone data update, form will use updated data on next open"
    );
    // 这里不需要主动刷新，因为每次打开表单时都会重新获取数据
    // 但可以通过emit通知父组件刷新数据
    emit("refresh-data");
  }
);

// 组件挂载时，如果是新增场景则获取用户号
onMounted(() => {
  if (isAdd.value && props.title !== "修改") {
    http
      .get(changeHttpLink("/api/User/user_no"))
      .then((res: any) => {
        if (res.Success) {
          newFormInline.value.no = res.Data.no;
        } else {
          ElMessage.error(res.Message);
        }
      })
      .catch(err => {
        ElMessage.error(err.message);
      });
  }
  newFormInline.value.power = 1;
  newFormInline.value.gps = 30;
  newFormInline.value.type = props.formInline.type === 2 ? 2 : 1;
});

function getFormData() {
  const formData = { ...newFormInline.value };

  // 处理过期时间：将选择的年份转换为 ISO 格式的日期字符串
  // if (formData.expire) {
  //   const currentDate = new Date();
  //   const years = parseInt(formData.expire.replace("year", ""));
  //   const expireDate = new Date(currentDate);
  //   expireDate.setFullYear(currentDate.getFullYear() + years);
  //   formData.expire = expireDate.toISOString();
  // }

  return formData;
}

function getRef() {
  return ruleFormRef.value;
}

defineExpose({ getRef, getFormData });
</script>

<style scoped>
.form-container {
  position: relative;
  max-height: 65vh; /* 设置最大高度为视口高度的70% */
  padding-right: 10px; /* 为滚动条预留空间 */
  overflow-y: auto; /* 启用垂直滚动条 */
}

/* 自定义滚动条样式 */
.form-container::-webkit-scrollbar {
  width: 6px;
}

.form-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.form-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.form-container::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}

.section-title {
  margin-top: 25px;
  margin-bottom: 25px;
  font-size: 16px;
  font-weight: bold;
  color: #333;
  text-align: center;
}

::v-deep.el-divider--horizontal {
  margin-top: 35px;
  margin-bottom: 35px;
}
</style>
